
## Replication code for "City Limits to Partisan Polarization" by Amalie Jensen,
## William Marble, Kenneth Scheve, and Matthew Slaughter



# This file runs all the analyses for the hierarchical model of conjoint responses
# found in Section 5. Make sure to run 00master1.do first since that cleans 
# the survey data.

# The hierarchical model is implemented in Stan and run via the rstan package. 
# For help installing RStan:
# https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started

# This code takes a very long time to run (several days) and will 
# use up *all* your computer resources by default. You can change the number of 
# cores used by editing 02run_demo_socioecon_pid7.R (see instructions there). 
# Please run this on a computer with sufficient RAM. We ran this on a 
# Lenovo ThinkCenter w/ an 8-core i7 processor and 16GB of RAM which is 
# probably the minimum RAM you can get away with.


setwd("D:/Dropbox/Cities/Publication_Files")

# Save output log
sink("Output/Results2.txt", append = FALSE)


# Install packages --------------------------------------------------------

pkgs = c("readstata13", "dplyr", "MASS", "ggpubr", "Hmisc", "ggplot2", 
         "ggthemes", "ggridges", "stringr", "parallel", "assertthat")

for (p in pkgs){
  if(!require(p, character.only = TRUE)) {
    install.packages(p)
    require(p, character.only = TRUE)
  }
}

if(!require(wpmarble)){
  devtools::install_github("wpmarble/wpmarble")
  require(wpmarble)
}



# Run scripts -------------------------------------------------------------

# Estimate model -- this takes forever.
source("Code/hlm/02run_demo_socioecon_pid7.R", echo = TRUE)
rm(list=ls())


# Analyze the results, make Fig. 5 and regression tables in appendix 
# error on first call to make_table
source("Code/hlm/03analyze_pid7_socioecon.R", echo = TRUE, max.deparse.length = Inf)
rm(list=ls())

sink("Output/Results2.txt", append = TRUE)
# Make Fig. 4 and Table 2
source("Code/hlm/04plot_imces.R", echo = TRUE, max.deparse.length = Inf)
rm(list=ls())

# Check convergence of MCMC 
source("Code/hlm/99check_convergence.R", echo = TRUE, max.deparse.length = Inf)
rm(list=ls())


sink(NULL)

